package com.hong.disconf;

import com.baidu.disconf.client.addons.properties.ReloadingPropertyPlaceholderConfigurer;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Spring加载bean之前添加disconf配置文件
 *
 * @author zengzh
 */
public class DisconfPropertyConfigurer extends ReloadingPropertyPlaceholderConfigurer {

    private Properties[] properties;

    @Override
    public void setPropertiesArray(Properties[] propertiesArray) {
        super.setPropertiesArray(propertiesArray);
        this.properties = propertiesArray;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        super.setApplicationContext(applicationContext);
        ConfigurableEnvironment environment = (ConfigurableEnvironment) applicationContext.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        Map<String, Object> encryptorMap = new HashMap<>(1);
        encryptorMap.put("jasypt.encryptor.password", "zzh");
        MapPropertySource encryptorMapPropertySource = new MapPropertySource("config-encryptor", encryptorMap);
        propertySources.addLast(encryptorMapPropertySource);
        propertySources.addLast(new PropertiesPropertySource("config-base", properties[0]));
    }
}
